<?php

namespace App\Http\Middleware;

use App\Constants\ErrorCode;
use App\Dto\AuthDto;
use App\Models\Site\SiteModel;
use App\Models\Site\SiteUserModel;
use Illuminate\Auth\AuthenticationException;

class JwtAuthenticate extends \Tymon\JWTAuth\Http\Middleware\Authenticate
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return null|string
     */
    public function handle($request, \Closure $next)
    {
        $user = auth()->user();
        if (blank($user)) {
            throw new AuthenticationException();
        }

        if (!is_super($user)) {
            if ($user->status != SiteUserModel::STATUS_T) {
                throw new \Exception('员工已禁用!',ErrorCode::CODE_ERROR_403);
            }

            if ($user->site->status != SiteModel::STATUS_T) {
                throw new \Exception('服务商已禁用!',ErrorCode::CODE_ERROR_403);
            }
        }

        //初始化dto
        AuthDto::setUser($user);
        AuthDto::setSiteInfo($user->site);
        AuthDto::setSiteId($user->site_id);
        AuthDto::setPlatform();
        // 验证token有效性
        return parent::handle($request, $next);
    }
}
